package chooongg.base

import android.app.Activity
import android.app.Application
import android.os.Bundle
import java.util.*

object Utils {

    fun initialize(application: Application) {
        this.app = application
        application.registerActivityLifecycleCallbacks(AppActivityLifecycle())

    }

    lateinit var app: Application
        private set

    val activityStack = LinkedList<Activity>()

    var activityCount = 0
        private set

    var appIsForeground = false
        private set

    val activityTop: Activity? get() = activityStack.last

    private class AppActivityLifecycle : Application.ActivityLifecycleCallbacks {

        override fun onActivityCreated(activity: Activity, saveInstanceState: Bundle?) {
            activityStack.add(activity)
        }

        override fun onActivityStarted(activity: Activity) {
            if (activityCount == 0) {
                appIsForeground = true
                appForegroundChangeCallback?.invoke(appIsForeground)
            }
            activityCount++
        }

        override fun onActivityResumed(activity: Activity) {
        }

        override fun onActivityPaused(activity: Activity) {
        }

        override fun onActivityStopped(activity: Activity) {
            activityCount--
            if (activityCount == 0) {
                appIsForeground = false
                appForegroundChangeCallback?.invoke(appIsForeground)
            }
        }

        override fun onActivityDestroyed(activity: Activity) {
            activityStack.remove(activity)
        }

        override fun onActivitySaveInstanceState(activity: Activity, saveInstanceState: Bundle?) {
        }
    }

    private var appForegroundChangeCallback: ((isForeground: Boolean) -> Unit)? = null

    fun setAppForegroundChangeCallback(appForegroundChangeCallback: (isForeground: Boolean) -> Unit) {
        this.appForegroundChangeCallback = appForegroundChangeCallback
    }
}